package titt.io.encoding.stringable;

import java.net.URLEncoder;

import titt.config.ValueConfig;
import titt.io.encoding.Encoder;
import titt.type.Type;
import titt.type.Types;
import titt.util.Bytes;

public class AsStringEncoder implements Encoder {

	@Override
	public byte[] encode(Type t, Object o) {
		try {
			if(t.equals(Types.STRING) && (o == null))
				return Bytes.asBytes(Types.NULL_TOKEN);

			if(t.equals(Types.STRING) && ((String)o).isEmpty())
				return Bytes.asBytes(Types.EMPTY_STRING_TOKEN);

			return Bytes.asBytes(enc(""+o));
		}
		catch(Exception e) {
			return Bytes.asBytes(""+o);
		}
	}
	
	private String enc(String s) throws Exception { 
		return URLEncoder.encode(s, ValueConfig.get().getCharset().displayName())
        .replaceAll("\\+", "%20")
        .replaceAll("\\%21", "!")
        .replaceAll("\\%27", "'")
        .replaceAll("\\%28", "(")
        .replaceAll("\\%29", ")")
        .replaceAll("\\%7E", "~");
	}
	
	@Override
	public boolean isEncodeable(Type t) {
		return t.equalsAny(Types.STRING, Types.BOOLEAN, Types.CHAR, Types.DOUBLE, 
					Types.FLOAT, Types.INT, Types.LONG, Types.SHORT, Types.BYTE);
	}

}
